package com.blog.cloud.monitor.vo;

import cn.hutool.system.oshi.OshiUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import oshi.software.os.OSFileStore;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 服务器信息对象
 */
@Slf4j
@Getter
@Setter
public class ServerVO {

    /**
     * CPU信息
     */
    @Schema(description = "CPU信息")
    private CpuVO cpu;

    /**
     * 内存信息
     */
    @Schema(description = "内存信息")
    private RamVO ram;

    /**
     * JVM信息
     */
    @Schema(description = "JVM信息")
    private JvmVO jvm;

    /**
     * 操作系统信息
     */
    @Schema(description = "系统信息")
    private SysVO sys;

    /**
     * 磁盘信息
     */
    @Schema(description = "系统磁盘信息")
    private List<DiskVO> disks = new LinkedList<>();

    public ServerVO() {
        log.info("begin to prepare server data");
        this.setCpu(new CpuVO());
        this.setSys(new SysVO());
        this.setRam(new RamVO());
        this.setJvm(new JvmVO());
        this.setDisks(getDiskStores());
    }

    public ServerVO(String description) {
        log.info("begin to prepare server data，the description is {}", description);
        this.setDisks(getDiskStores());
    }

    /**
     * 组装系统所有磁盘信息
     */
    private List<DiskVO> getDiskStores() {
        List<DiskVO> diskVOS = new ArrayList<>();
        // 获取服务器的所有系统磁盘
        List<OSFileStore> fileStores = OshiUtil.getOs().getFileSystem().getFileStores();
        fileStores.forEach(osFileStore -> {
            DiskVO diskVO = new DiskVO();
            diskVO.setDiskName(osFileStore.getName());
            diskVO.setDiskType(osFileStore.getType());
            diskVO.setTotal(osFileStore.getTotalSpace());
            diskVO.setFree(osFileStore.getFreeSpace());
            diskVO.setUsed(osFileStore.getUsableSpace());
            long usage = (osFileStore.getUsableSpace() % osFileStore.getTotalSpace()) * 100;
            diskVO.setUsage(usage);
            diskVOS.add(diskVO);
        });
        return diskVOS;
    }
}
